package uutalk.netcloud.talk.base.android;

/**
 * Created by hujie on 16/5/29.
 */

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.yatatsu.autobundle.AutoBundle;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import onactivityresult.ActivityResult;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.util.ProgressHudUtil;
import uutalk.netcloud.talk.base.util.thirdpart.BugtagsManager;

/**
 * Created by hujie on 16/5/24.
 * <p>
 * 基础Activity activity的类已A 开头
 */
public abstract class BaseActivity extends RxAppCompatActivity implements IUI {

    public Activity mActivity;
    private LinearLayout mRootView;
    private Unbinder unbinder;
    private Toolbar mToolbar;
    private TextView mTitleTV;
    public ProgressHudUtil progressHudUtil;
    private Handler mHandler;
    public String TAG;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        setTheme();
        setWindowsFeature();
        super.onCreate(savedInstanceState);

        mActivity = this;
        progressHudUtil = new ProgressHudUtil(mActivity);
        setUpView(layoutId());
        setSupportActionBar();
        bindView();
        setStatusColor();
        bindBundle(savedInstanceState);
        bindEvent();
        mHandler = new MyHandler(this);
        TAG = this.getClass().getName();
        init();
    }


    public abstract void init();


    //添加自定义菜单
    public void addCustomMenu(View menuView) {
        if (supportActionbar()) {
            LinearLayout menuLayout = (LinearLayout) findViewById(R.id.menuView);
            menuLayout.setVisibility(View.VISIBLE);
            menuLayout.removeAllViews();
            menuLayout.addView(menuView);
        }
    }

    public void setStatusColor() {
        //5.0上面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            addStatusView(R.color.colorPrimaryDark);
        }

    }

    View mStatusBarTintView;

    public void addStatusView(int color) {
        if (mRootView != null) {
            mRootView.setFitsSystemWindows(false);
            int statusHeight = getStatusHeight();
            mStatusBarTintView = new View(this);
            mStatusBarTintView.setAlpha(0.8f);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, statusHeight);
            mStatusBarTintView.setLayoutParams(params);
            mStatusBarTintView.setBackgroundColor(getResources().getColor(color));
            mStatusBarTintView.setVisibility(View.VISIBLE);
            mRootView.addView(mStatusBarTintView, 0);
        }

    }

    /**
     * 获取状态栏高度
     * @return
     */
    public static int getStatusHeight() {
        return getInternalDimensionSize(Resources.getSystem(), "status_bar_height");
    }

    private static int getInternalDimensionSize(Resources res, String key) {

        int result = 0;
        int resourceId = res.getIdentifier(key, "dimen", "android");
        if (resourceId > 0) {
            result = res.getDimensionPixelSize(resourceId);
        }

        return result;
    }

    @Override
    public void bindBundle(Bundle savedInstanceState) {
        if (autoBindBundle()) {
            if (savedInstanceState == null) {
                AutoBundle.bind(this);
            } else {
                AutoBundle.bind(this, savedInstanceState);
            }
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (autoBindBundle()) {
            AutoBundle.pack(this, outState);
        }
    }

    /**
     * When use AutoBundle to inject arguments, should override this and return {@code true}.
     */
    protected boolean autoBindBundle() {
        return false;
    }


    /**
     * 是否支持toolbar作为导航栏
     * 如果不需要导航栏 则return false
     *
     * @return
     */
    public boolean supportActionbar() {
        return true;
    }


    /**
     * 设置toobar作为导航栏
     */
    public void setSupportActionBar() {
        if (supportActionbar()) {
            mToolbar = (Toolbar) findViewById(R.id.actionbar);
            mTitleTV = (TextView) mToolbar.findViewById(R.id.toolbarTitleTV);
            setSupportActionBar(mToolbar);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            setBackNavication();
        }
    }


    /**
     * 是否显示返回按钮
     *
     * @return
     */
    public boolean showBackNavication() {
        return true;
    }

    /**
     * 设置返回导航
     */
    public void setBackNavication() {
        if (showBackNavication()) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationContentDescription("返回");
            mToolbar.setNavigationOnClickListener(v -> onBackPressed());
        } else {
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        }
    }


    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        if (supportActionbar() && mTitleTV != null) {
            if (color != 0) {
                mTitleTV.setTextColor(color);
            }
            mTitleTV.setText(title);
        }
    }

    /**
     * 设置主题
     * 默认采用AppTheme主题
     */
    private void setTheme() {
        if (getThemeId() != 0) {
            setTheme(getThemeId());
        }
    }


    /**
     * 获取自定义主题ID
     *
     * @return
     */
    public int getThemeId() {
        return R.style.AppTheme;
    }


    @Override
    public void setUpView(@LayoutRes int layoutId) {
        if (layoutId != 0) {
            mRootView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.root_layout,
                    null);
            if (supportActionbar()) {
                View toolBarView = LayoutInflater.from(this).inflate(R.layout.actionbar, null);
                mRootView.addView(toolBarView);
            }
            View contentView = LayoutInflater.from(this).inflate(layoutId, null);
            mRootView.addView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                    .MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            setContentView(mRootView);
        }
    }

    @Override
    public void bindView() {
        if (autoBindViews()) {
            unbinder = ButterKnife.bind(this);
        }
    }

    /**
     * 是否绑定事件
     * 默认不绑定
     *
     * @return
     */
    public boolean autoBindEvent() {
        return false;
    }

    @Override
    public void bindEvent() {
        if (autoBindEvent()) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * 是否自动绑定view
     * 默认采用butterknife进行view的注入
     *
     * @return
     */
    public boolean autoBindViews() {
        return true;
    }

    @Override
    public void unBindView() {
        if (autoBindViews() && unbinder != null) {
            unbinder.unbind();
        }
    }


    @Override
    public void unBindEvent() {
        if (autoBindEvent()) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 避免内存泄漏

        gc();
    }

    public void setWindowsFeature() {

        // 强制竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 去掉标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);

    }


    @Override
    protected void onActivityResult(final int requestCode, final int resultCode,
                                    final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (handleActivityResult()) {
            ActivityResult.onResult(requestCode, resultCode, data).into(this);
        }
    }


    public View getRootView() {
        return mRootView;
    }


    /**
     * 有返回值
     *
     * @return
     */
    protected boolean handleActivityResult() {
        return false;
    }


    /**
     * 内存释放等
     */
    public void gc() {
        if (progressHudUtil != null) {
            progressHudUtil.dismissProgressHud();
            progressHudUtil.destory();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        unBindView();
        unBindEvent();

        mActivity = null;
        unbinder = null;
        mRootView = null;
    }


    /**
     * 获取到布局id
     *
     * @return
     */
    public abstract int layoutId();


    @Override
    protected void onResume() {
        super.onResume();
        //注：回调 1
        BugtagsManager.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注：回调 2
        BugtagsManager.onPause(this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        BugtagsManager.onDispatchTouchEvent(this, event);
        return super.dispatchTouchEvent(event);
    }



    private static final class MyHandler extends Handler {
        private WeakReference<BaseActivity> mBaseActivity;

        public MyHandler(BaseActivity baseActivity) {
            mBaseActivity = new WeakReference<>(baseActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mBaseActivity != null) {
                BaseActivity baseActivity = mBaseActivity.get();
                if (baseActivity != null) {
                    baseActivity.handleMessage(msg);
                }
            }
        }
    }

    public void handleMessage(Message msg) {
    }

    public void sendEmptyMessageToPage() {
        mHandler.obtainMessage().sendToTarget();
    }

    public void sendMessageToPage(int what) {
        mHandler.obtainMessage(what).sendToTarget();
    }

    public void sendMessageToPageDelay(int what, long delay) {
        mHandler.sendEmptyMessageDelayed(what, delay);
    }

    public void sendMessageToPage(int what, Object obj) {
        mHandler.obtainMessage(what, obj).sendToTarget();
    }

    public void sendMessageToPage(int what, int arg1, int arg2) {
        mHandler.obtainMessage(what, arg1, arg2).sendToTarget();
    }

    public void sendMessageToPage(int what, int arg1, int arg2, Object obj) {
        mHandler.obtainMessage(what, arg1, arg2, obj).sendToTarget();
    }

    public void sendMessageToPage(Message msg, long delayMillis) {
        mHandler.sendMessageDelayed(msg, delayMillis);
    }


    public void removeMessageFromPage(int what) {
        mHandler.removeMessages(what);
    }


}


